// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  let {
    dsName,
    ids,
    where,
    data
  } = event
  where = where || {}

  try {
    if (where._openid) {
      if (where._openid === true) where._openid = openid
      return await db.collection(dsName).where(where).update({
        data
      })
    }

    if (ids) where._id = _.in(ids)
    return db.collection(dsName).where(where).update({
      data
    })
  } catch (e) {
    console.error(e)
    return e
  }
}